package com.study.filter;

import com.study.bean.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    // ServletRequest servletRequest = new HttpServletRequest()
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        System.out.println("requestURI:" + requestURI);
        String method = request.getParameter("method");
        //这是请求是要去完成登录的，不需要执行后面验证是否登录的流程
        if (requestURI.startsWith("/static")
                || requestURI.equals("/page/login")
                || requestURI.equals("/verifyCode")
                || requestURI.equals("/user") && "login".equals(method)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("/page/login");
            return;
        }

        //加了这句话代表方行，继续往后执行，
        //如果还有filter就访问后面filter，没有filter，就可以访问后台资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}